import React from 'react'
import { Spin, Alert  } from 'antd';
import MovieItem from './movieItem.jsx';
import { Pagination } from 'antd';
import fetchJSONP from 'fetch-jsonp'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
export default class movieList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      movies: [],
      nowPage: parseInt(props.match.params.page) || 1, // 当前展示第几页的数据,
      pageSize: 15,
      total: 0,
      isloading: true,
      movieType: props.match.params.type
    }
  }
  componentWillMount() {
  
    this.loadMovieListByTypeAndPage()
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      isloading:true,
      nowPage: parseInt(nextProps.match.params.page) || 1, // 要获取第几页的数据
      movieType: nextProps.match.params.type // 电影类型
    },function(){
      this.loadMovieListByTypeAndPage()
    })
  }
  componentDidUpdate (){
    
  }
  render() {
    return <div>
      {this.renderList()}
    </div>
    
  }
  loadMovieListByTypeAndPage = () => {
    const start = this.state.pageSize * (this.state.nowPage - 1)
    const url = `https://api.douban.com/v2/movie/${this.state.movieType}?start=${start}&count=${this.state.pageSize}`
    fetchJSONP(url).then(response => response.json())
      .then(data => {
        this.setState({
          movies: data.subjects,
          isloading: false,
          total: data.total
        })
        NProgress.done(true)
      })
    /* const data = require('../test_data/' + this.state.movieType + '.json')
    setTimeout(() => {
      this.setState({
        movies: data.subjects,
        isloading: false,
        total: data.total
      })
    }) */
  }
  renderList = () => {
    if (this.state.isloading) {
      return <Spin tip="Loading...">
        <Alert
          message="Alert message title"
          description="Further details about the context of this alert."
          type="info"
        />
      </Spin>
    } else {
      return <div>
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
          {this.state.movies.map(item =>{
            return <MovieItem {...item} key={item.id} history={this.props.history}></MovieItem>
          })}
        </div>
        <Pagination defaultCurrent={this.state.nowPage} pageSize={this.state.pageSize} onChange={this.onChange}  size="small" total={this.state.total} showSizeChanger showQuickJumper />
      </div>

    }
  }
  onChange = (pageNumber) => {
    console.log('Page: ', pageNumber);
    this.props.history.push('/movie/' + this.state.movieType + '/' + pageNumber)
  }
}